<template>
  <view class="content">
    <h3 class="title">账号登录</h3>
    <view class="input-group">
      <input type="tel" placeholder="手机号码" v-model="phoneNumber" focus></input>
    </view>
    <view class="input-group">
      <input type="password" placeholder="密码" v-model="password"></input>
    </view>
    <button class="login-btn" @tap="handleLogin">登录</button>
  </view>
</template>

<script>
import { login } from '@/api/index.js';
export default {
  data() {
    return {
      phoneNumber: '',
      password: '',
      canLogin: true,
      validCode: "",
    };
  },
  methods: {
    async handleLogin() {
      if (!this.phoneNumber || !this.password) {
        showErrorToast('请填写完整手机号和密码');
        return;
      }
      uni.showLoading({
          title: '登录中...',
        });
      this.canLogin = false;
      const loginData = {
        username: this.phoneNumber,
        password: this.password,
        validCode: this.validCode,
        loginType: "1"
      };
      try {
        const ret = await login(loginData)
        uni.setStorageSync('token', ret.token);
        uni.setStorageSync('craft', ret.processes[0].name);
        uni.setStorageSync('username', ret.user.phonenumber);
        uni.hideLoading();
        if (ret.processes[0].name == '包装') {
          uni.setStorageSync('nickName', ret.user.nickName);
          navigateAfterSuccess('/pages/package/index');
        } else {
          navigateAfterSuccess('/pages/add/index');
        }
      } catch (error) {
        uni.showToast({
        title: '登录失败',
        icon: "error",
        duration: 1000, // 自定义持续时间
    });
      }
    }
  }
};

function showErrorToast(message) {
  uni.showToast({
    icon: 'none',
    title: message,
  });
}

function navigateAfterSuccess(pageurl) {
  // 显示登录成功提示
  uni.showToast({
    title: '登录成功',
    icon: 'success',
    duration: 1000, // 自定义持续时间
  });
  // 使用 Promise 链接，等待提示消失后跳转
  new Promise((resolve) => setTimeout(resolve, 1500))
    .then(() => {
      uni.navigateTo({
        url: pageurl,
      });
    });
}
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.title {
  font-size: 24px;
  color: #333;
  margin-bottom: 40px;
}

.input-group {
  width: 80%;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.input-group input {
  width: 100%;
  border: none;
  outline: none;
  font-size: 16px;
  color: #333;
}

.login-btn {
  width: 84%;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 18px;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.login-btn:hover {
  background-color: #0056b3;
}
</style>